package me.zhengjie.minbearwcs.serivce.rework;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.minbearwcs.dao.rework.inf.ReworkOrderDao;
import me.zhengjie.minbearwcs.dao.rework.inf.ReworkOrderDetailDao;
import me.zhengjie.minbearwcs.entity.DTO.response.Resp;
import me.zhengjie.minbearwcs.entity.DTO.rework.wms.order.WmsReworkOrder;
import me.zhengjie.minbearwcs.entity.DTO.transfer.Tuple;
import me.zhengjie.minbearwcs.entity.PO.wcs.rework.ReworkOrder;
import me.zhengjie.minbearwcs.entity.PO.wcs.rework.ReworkOrderDetail;
import me.zhengjie.minbearwcs.entity.PO.wcs.rework.status.ReworkOrderDetailStatus;
import me.zhengjie.minbearwcs.entity.PO.wcs.rework.status.ReworkOrderStatus;
import me.zhengjie.minbearwcs.serivce.mission.generate.MissionGeneratorCollector;
import me.zhengjie.minbearwcs.serivce.mission.generate.type.MissionGenType;
import me.zhengjie.minbearwcs.utils.IdWorker;
import me.zhengjie.minbearwcs.utils.WcsHpptUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class ReworkService {

    private final ReworkOrderDao reworkOrderDao;
    private final ReworkOrderDetailDao reworkOrderDetailDao;
    private final IdWorker idWorker;
    private final MissionGeneratorCollector missionGeneratorCollector;


    @Transactional
    public Tuple<String> reworkOrderReceive(WmsReworkOrder wmsReworkOrder) {
        ReworkOrder reworkOrder = new ReworkOrder(null, wmsReworkOrder.getReworkOrderCode(), wmsReworkOrder.getOrderType(), ReworkOrderStatus.PROCESSING,
                LocalDateTime.now(), LocalDateTime.now(), null);
        reworkOrderDao.insert(reworkOrder);

        List<String> palletList = wmsReworkOrder.getPalletList();
        List<ReworkOrderDetail> reworkOrderDetails = new ArrayList<>();
        for (String pallet : palletList) {
            ReworkOrderDetail reworkOrderDetail = new ReworkOrderDetail(null, "rework_detail_" + idWorker.nextId(), wmsReworkOrder.getReworkOrderCode(), pallet,
                    ReworkOrderDetailStatus.INIT, null, null, null);

            reworkOrderDetailDao.insert(reworkOrderDetail);
            reworkOrderDetails.add(reworkOrderDetail);
        }

        missionGeneratorCollector.getGenerator(MissionGenType.REWORK).generate(reworkOrderDetails);

        return Tuple.tuple(null, true);
    }

}
